package cn.lili.feign;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.lili.common.enums.ResultCode;
import cn.lili.common.exception.ServiceException;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import org.springframework.context.annotation.Configuration;

import java.nio.charset.Charset;

/**
 * 转发服务调用时的触发异常
 *
 * @author paulG
 * @since 2022/7/27
 **/
@Configuration
public class FeignErrorDecoder implements ErrorDecoder {

    @Override
    public Exception decode(final String methodKey, final Response response) {
        try {
            //503 服务找不到抛出异常
            if(response.status()==503){
                return new ServiceException(ResultCode.ERROR);
            }
            //自定义异常判定
            String message = Util.toString(response.body().asReader(Charset.defaultCharset()));
            JSONObject jsonObject = JSONUtil.parseObj(message);
            if (jsonObject.containsKey("code")) {
                return new ServiceException(ResultCode.getResultByCode(jsonObject.getInt("code")), jsonObject.getStr("message"));
            }
        }
//        自定义异常则直接返回
        catch (ServiceException ignored) {
            return ignored;
        }
//        未知异常打印然后抛出默认异常
        catch (Exception e) {
            e.printStackTrace();
        }
        return new ServiceException();
    }
}
